package com.qqt.csr.web.mq;

import com.qqt.csr.common.utils.CacheKeyUtil;
import com.qqt.csr.common.utils.JsonUtil;
import com.qqt.csr.common.utils.RedissonLockUtil;
import com.qqt.csr.im.socketio.constants.EventsConstants;
import com.qqt.csr.route.dto.resp.RouteResultDTO;
import com.qqt.csr.route.entity.RouteTask;
import com.qqt.csr.route.service.RouteMqProducerService;
import com.qqt.csr.web.service.AcceptingConversationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author:
 * @Date:
 * @Description: 路由任务结果处理
 **/
@Slf4j
@Service
@RocketMQMessageListener(
        consumerGroup = "${rocketmq.consumer.group}_route_result",
        topic = RouteMqProducerService.ROUTE_DISTRIBUTE_RESULT_TOPIC,
        tlsEnable = "${rocketmq.consumer.tlsEnable}"
)
public class RouteResultHandlerListener implements RocketMQListener<String> {
    @Autowired
    private AcceptingConversationService acceptingConversationService;
    @Autowired
    private RedissonLockUtil redissonLockUtil;

    @Override
    public void onMessage(String data) {
        if (StringUtils.isBlank(data)) {
            return;
        }
        try {
            RouteResultDTO resultDTO = JsonUtil.toObject(data, RouteResultDTO.class);
            if (resultDTO == null || resultDTO.getRouteTaskDTO() == null) {
                return;
            }
            String cacheKey = String.format(CacheKeyUtil.SkillSet.ROUTE_TASK_RESULT_LOCK, resultDTO.getRouteTaskDTO().getRouteTaskId());
            redissonLockUtil.distributedLock(() -> {
                acceptingConversationService.handleRouteResult(resultDTO);
            }, cacheKey, 0, 30, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("路由任务结果处理失败！data:{}", data, e);
        }
    }

}
